<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed } from 'vue'
import { useRoute } from 'vue-router';
import { useTokenStore } from '../../stores/token'
import { useUserInfoStore } from '../../stores/userInfo'
import {
  getByIdAssService,
  addStudentAssService,
  updateStudentAssService,
  getByIdService
} from '../../api/studentAss'
const route = useRoute();
const userInfoStore = useUserInfoStore()
import { getStudentByIdService} from '../../api/student'
import { getByIdAssignmentService} from '../../api/assignment'
import { addAssCorrectService} from '../../api/assCorrect'
import { getassAllocationService,updateassAllocationService} from '../../api/assAllocation'
const searchQuery = ref('') // 新增的搜索条件

const filteredNotices = computed(() => {
  return studentAsss.value.filter(studentAss =>
    studentAss.info.includes(searchQuery.value)
  )
})

const studentAsss = ref([])
// 弹框标题
const title = ref('')
const imageUrl = ref('');
const assignmentTitle = ref(''); // 或者通过其他逻辑获取作业名称
//控制添加学生作业弹窗
const imgTableVisible = ref(false)
const fileName = ref(''); // 新增：用于存储文件名
// 学生作业表单模型
const studentAssModel = ref({
  title: '',
  info: '',
  score: 0,
  id: '',
})

// 显示学生作业列表信息
const studentAssList = async () => {
  const assignmentId = computed(() => route.query.assId); // 获取 assignmentId
  const stuId = userInfoStore.userInfo.id; // 获取当前用户的 id
  
  // 构建 pageData 对象
  const pageData = {
    assClass: assignmentId.value,
    stuId: stuId,
  };
  let task = await getassAllocationService(pageData);
  const AssTasksArray = []; // 修改命名以避免重复
  for (const item of task.data) {
    let res = await getByIdService(item.assId); // 使用 assId 查询作业信息
    // 将获取到的作业信息添加到数组中
    if (res.data) {
      AssTasksArray.push({
      ...res.data,
      status: item.status 
    });
    }
  }
  const studentAsssData = AssTasksArray;
  const Promises = studentAsssData.map((studentAss, index) => {
    return getByIdAssignmentService(studentAss.assId).then(assignmentResponse => {
      const anonymousStudentName = `学生${index + 1}`;
      return {
        ...studentAss,
        student: anonymousStudentName, // 使用匿名学生名字
        assignmentTitle: assignmentResponse.data.title // 添加作业名字
      };
    });
  });
  studentAsss.value = await Promise.all(Promises);
};

import * as XLSX from 'xlsx';
const handleImageError = () => {
  // 当图片加载失败时，将 imageUrl 设置为空字符串
  imageUrl.value = '';
};
// 导出成绩
const exportFile = () => {
  // 获取需要导出的数据
  const dataToExport = filteredNotices.value.map(studentAss => ({
    作业名: studentAss.title,
    学生名: studentAss.student,
    附加内容: studentAss.info,
    成绩: studentAss.score,
  }));

  // 创建工作簿
  const worksheet = XLSX.utils.json_to_sheet(dataToExport);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '学生作业成绩');

  // 导出 Excel 文件
  XLSX.writeFile(workbook, '学生作业成绩.xlsx');
};

// 提取文件名和后缀
const extractFileName = (fileLink) => {
  const url = new URL('/api' + fileLink, window.location.origin);
  const params = new URLSearchParams(url.search);
  return params.get('fileName') || '未知文件名';
};
//查看作业
const showAssignment = async(row) => {
  const file = row.file;
  studentAssModel.value.assId = row.id;
  imgTableVisible.value=true
  // 如果有文件链接，尝试获取图片并设置到 imageUrl
  if (file) {
    try {
      const response = await fetch('/api' + file, {
        headers: {
          Authorization: `${useTokenStore().token}`,
        },
      });
      if (!response.ok) throw new Error('Network response was not ok');
      const blob = await response.blob();
      imageUrl.value = URL.createObjectURL(blob);
      fileName.value = extractFileName(file); // 设置文件名
    } catch (error) {
      console.error('Failed to load image:', error);
      imageUrl.value = ''; 
    }
  } else {
    imageUrl.value = ''; // 没有文件时清除 imageUrl
  }
}
// 下载
const downloadFile = (fileLink) => {
  console.log(fileLink.file);
  const fileUrl = fileLink.file;
  fetch('/api' + fileUrl, {
    method: 'GET',
    headers: {
      'Authorization': `${useTokenStore().token}`
    }
  })
  .then(response => {
    if (!response.ok) {  // 检查响应状态
      throw new Error(`下载失败，状态码: ${response.status}`); // 输出失败原因
    }
    return response.blob(); // 将响应转换为 Blob 对象
  })
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = fileUrl.split('/').pop(); // 指定下载的文件名和扩展名
    document.body.appendChild(a);
    a.click(); // 自动点击下载链接
    document.body.removeChild(a); // 下载后移除链接元素
    window.URL.revokeObjectURL(url); // 释放对象 URL
  })
  .catch(error => {
    // 改进的错误处理
    console.error('下载过程中出现问题:', error);
    ElMessage({
      message: '下载失败，请重试。',
      type: 'error',
    });
  });
}
// 提交评分
const submitScore = async () => {
  studentAssModel.value.stuId = userInfoStore.userInfo.id;
  studentAssModel.value.status = 1;
  console.log(studentAssModel.value);
  try {
    // 发送评分请求
    let res = await addAssCorrectService(studentAssModel.value);
    let les = await updateassAllocationService(studentAssModel.value)
    ElMessage.success(res.message&&les.message ? res.message : '提交成功!');
    imgTableVisible.value = false;
    clearStudentAssModel();
    studentAssList();
  } catch (error) {
    imgTableVisible.value = false;

  }
}
//清空studentAssModel
const clearStudentAssModel = () => {
  studentAssModel.value = {
    title: '',
    info: '',
    score: 0,
    id: '',
  };
}
//返回上一页
const goBack = () => {  
  window.history.go(-1)
}
studentAssList()
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <el-page-header @back="goBack">
          <template #content>
            <span>{{ assignmentTitle }}</span>
          </template>
        </el-page-header>
        <div class="extra">
          <el-button @click="exportFile" type="primary">导出成绩</el-button>
        </div>
      </div>
    </template>
    <!-- 查看作业 -->
    <el-dialog v-model="imgTableVisible" title="评分" width="1000">
    <div class="dialog-content">
      <!-- 左侧内容 -->
      <div class="left-panel">
        <div class="image-section">
          <el-image 
            v-if="imageUrl"
            :src="imageUrl" 
            :preview-src-list="[imageUrl]"
            @error="handleImageError"
            class="student-image"
          >
          </el-image>
          <p class="file-name">{{ fileName }}</p>
        </div>

        <div class="scoring-guidelines">
          <h4>得分指导：</h4>
          <ul>
            <li>观点明确，论证清晰，有较强的合理性，分数大于等于85</li>
            <li>观点明确，论证较为清晰、完整，有一定合理性，分数大于70分</li>
            <li>认真回答作业提出的问题，没有主题、偏题现象，字数基本符合要求，分数大于60分</li>
          </ul>
        </div>

        <el-form label-width="80px" class="form-section">
          <el-form-item label="评分：" prop="score">
            <el-input-number v-model="studentAssModel.score" :min="1" :max="100" />
          </el-form-item>
          <el-form-item label="评语：">
            <el-input 
              type="textarea" 
              placeholder="请输入评语" 
              v-model="studentAssModel.info" 
              style="width: 100%;"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <!-- 右侧参考答案模块 -->
      <div class="right-panel">
        <h3>参考答案</h3>
        <p>这里是参考答案的内容，提供给学生以供参考。</p>
        <p>详尽阐述观点，确保涵盖所有相关要点，并提供相应的支持性论据。</p>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="success" @click="submitScore">提交</el-button>
        <el-button @click="imgTableVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>

    <!-- 列表 -->
    <el-table :data="filteredNotices" style="width: 100%">
      <el-table-column label="序号" width="70" type="index"></el-table-column>
      <el-table-column label="学生" prop="student"></el-table-column>
      <el-table-column label="附加内容" prop="info"></el-table-column>
      <el-table-column label="状态" prop="status">
        <template #default="{ row }">
          {{ row.status === 0 ? '未批改' : '已批改' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button v-if="row.status === 0" type="success" plain @click="showAssignment(row)">查看作业</el-button>
          <el-button v-if="row.status === 1" type="danger">已完成</el-button>
          <el-button @click="downloadFile(row)" type="text">下载查看</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.dialog-content {
  display: flex;
  justify-content: space-between;
}

.left-panel, .right-panel {
  flex: 1;
  padding: 20px;
  border: 1px solid #ebebeb;
  border-radius: 4px;
  background-color: #fff;
}

.left-panel {
  margin-right: 20px;
}

.image-section {
  text-align: center;
  margin-bottom: 20px;
}

.student-image {
  width: 200px;
  height: 200px;
  border-radius: 8px;
}

.file-name {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}

.scoring-guidelines h4 {
  margin-bottom: 10px;
}

.scoring-guidelines ul {
  list-style-type: disc;
  padding-left: 20px;
}

.form-section {
  margin-top: 20px;
}

.right-panel {
  padding-left: 20px;
}

.dialog-footer {
  text-align: right;
}

.el-textarea {
  width: 100%;
}
</style>
